/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import java.util.Calendar;
import javax.swing.JOptionPane;
import logic.Categoria;

/**
 * Clase JFrame encargada de recoger los datos para crear una Rifa. Tiene como 
 * atributos el GUI y un JPanelCategoría para seleccionar la categoría donde
 * se guardará la rifa.
 * @author Victoria Fuenmayor y Jose Gabriel Rivera
 */
public class JFrameRifa extends javax.swing.JFrame {
    private GUI gui;
    JPanelCategoria categorías;
    
    /**
     * Constructor. Recibe el GUI. Inicializa los componentes gráficos, ubica
     * el frame en una posición central en la pantalla, asigna el GUI y crea un 
     * nuevo JPanelCategoría para seleccionar la categoría donde se creará la rifa.
     * @param gui 
     */
    public JFrameRifa(GUI gui) {
        initComponents();
        this.setLocation(250, 150);
        
        this.gui = gui;
        categorías = new JPanelCategoria(gui.getCategoria(),gui){

            @Override
            public void evento() {
            }
            
        };
        categorías.CargarCat();
        this.add(categorías);
        categorías.setBounds(170, 45, 118, 20);        
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        nombreRifa = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        valorTicket = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        valorProducto = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        finicio = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        fsorteo = new javax.swing.JTextField();
        bCrear = new javax.swing.JButton();
        bCancelar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        descripcion = new javax.swing.JTextArea();

        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Ingrese los datos de la rifa");

        jLabel2.setText("Nombre");

        jLabel3.setText("Descripción");

        jLabel4.setText("Categoría");

        jLabel6.setText("Valor del ticket");

        jLabel7.setText("Costo del producto");

        jLabel8.setText("Fecha de inicio");

        finicio.setText("DD/MM/AAAA");

        jLabel9.setText("Fecha del sorteo");

        fsorteo.setText("DD/MM/AAAA");

        bCrear.setText("Crear");
        bCrear.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bCrearMouseClicked(evt);
            }
        });

        bCancelar.setText("Cancelar");
        bCancelar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bCancelarMouseClicked(evt);
            }
        });

        descripcion.setColumns(20);
        descripcion.setRows(5);
        descripcion.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jScrollPane1.setViewportView(descripcion);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(74, 74, 74)
                                .addComponent(bCrear, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(68, 68, 68)
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 95, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(valorTicket, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel6)
                    .addComponent(jLabel3)
                    .addComponent(jLabel9)
                    .addComponent(fsorteo)
                    .addComponent(nombreRifa))
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel4)
                    .addComponent(bCancelar)
                    .addComponent(finicio, javax.swing.GroupLayout.DEFAULT_SIZE, 117, Short.MAX_VALUE)
                    .addComponent(jLabel8)
                    .addComponent(jLabel7)
                    .addComponent(valorProducto, javax.swing.GroupLayout.DEFAULT_SIZE, 117, Short.MAX_VALUE))
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(nombreRifa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel6)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(valorTicket, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(valorProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(jLabel9))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(finicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(fsorteo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bCrear)
                    .addComponent(bCancelar))
                .addGap(6, 6, 6))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * MouseClicked para el boton cancelar. Oculta el JFrame al hacerle click.
     * @param evt 
     */
    private void bCancelarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bCancelarMouseClicked
        // TODO add your handling code here:
        this.setVisible(false);
    }//GEN-LAST:event_bCancelarMouseClicked

    /**
     * MouseCLicked para el boton crear rifa. Recoge todos los datos de la rifa en los 
     * texfields, los valida y si todos los campos fueron ingresados correctamente
     * se guarda la rifa en el BDRifas de la categoría seleccionada.
     * @param evt 
     */
    private void bCrearMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bCrearMouseClicked
        // TODO add your handling code here:
        
        String nombre = null,description = null;
        double ticket = 0,producto = 0;
        Calendar fechaIni = null,fechaFin = null;
        Categoria cat = null;
        boolean flag = true;
        
        if (nombreRifa.getText().length()>30){
            JOptionPane.showMessageDialog(this, "Error: Nombre sólo permite 30 caractéres.");  
            flag=false;
        }else if(descripcion.getText().length()>250){
            JOptionPane.showMessageDialog(this, "Error: Descripción sólo permite 250 caractéres.");  
            flag=false;
        }else{
            nombre = nombreRifa.getText();
            description = descripcion.getText();
        }
        
        try{       
            if (Double.parseDouble(valorTicket.getText()) >=0 ){
                ticket = Double.parseDouble(valorTicket.getText());
            }else{
                JOptionPane.showMessageDialog(this, "Error: El valor del ticket debe ser positivo");
                flag = false;
            }
        }
        catch(NumberFormatException e){
            JOptionPane.showMessageDialog(this, "Error: El valor del ticket debe tener formato numerico 123.4");
            flag=false;
        }
        try{
            if (Double.parseDouble(valorProducto.getText())>=0){
                producto = Double.parseDouble(valorProducto.getText());
            }else{
                JOptionPane.showMessageDialog(this, "Error: El valor del producto debe ser positivo");
                flag = false;
            }  
        }
        catch(NumberFormatException e){
            JOptionPane.showMessageDialog(this, "Error: El valor del producto debe tener formato numerico 123.4");
            flag=false;
        }
                
        if(categorías.getIdCat()>=0){
            cat = (logic.Categoria)gui.getCategoria().getObject(categorías.getIdCat());
            if (cat.getRifas().buscarObjeto(nombreRifa.getText())!=null){
            JOptionPane.showMessageDialog(this, "Error: Ya existe el nombre de la rifa.");
            flag=false;
        }
        }else{
            JOptionPane.showMessageDialog(this, "Error: Debe seleccionar una categoría");
            flag = false;
        }
        
        try{
            fechaIni = logic.LibreriaCalendario.stringToCalendar(finicio.getText());
            fechaFin = logic.LibreriaCalendario.stringToCalendar(fsorteo.getText());
            
            if (logic.LibreriaCalendario.validarFecha(finicio.getText()) == false || logic.LibreriaCalendario.validarFecha(fsorteo.getText()) == false ){
                JOptionPane.showMessageDialog(this, "Error: Fecha inválida.");
                flag = false;
            }
            
        }catch(Exception e){
            JOptionPane.showMessageDialog(this, "Error: Fecha inválida.");
            flag=false;
        }
        
        if (flag == true){
            cat.newRifa(nombre, description, cat, ticket, producto, fechaIni, fechaFin);    
            this.setVisible(false);
        }
               
    }//GEN-LAST:event_bCrearMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JFrameRifa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFrameRifa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFrameRifa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrameRifa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JFrameRifa(new GUI("Raffle System")).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bCancelar;
    private javax.swing.JButton bCrear;
    private javax.swing.JTextArea descripcion;
    private javax.swing.JTextField finicio;
    private javax.swing.JTextField fsorteo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField nombreRifa;
    private javax.swing.JTextField valorProducto;
    private javax.swing.JTextField valorTicket;
    // End of variables declaration//GEN-END:variables
}
